package com.admission.service;

import java.io.File;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;

import com.admission.dao.SpecialAttachmentDao;
import com.admission.model.SpecialAttachment;
import com.admission.util.DeleteFile;

@Repository
@Transactional
public class SpecialAttachmentManager {
	private SpecialAttachmentDao specialAttachmentDao;

	/**
	 * 通过id找唯一对象，无返回null
	 * 
	 * @param id
	 * @return
	 */
	public SpecialAttachment getById(String id) {
		return specialAttachmentDao.findUniqueBy("id", id);
	}

	/**
	 * 保存、更新
	 * 
	 * @param Entity
	 * @return
	 */
	public void save(SpecialAttachment entity, String url) throws Exception {
		String serverrealPath = ServletActionContext.getServletContext()
				.getRealPath("/upload");
		if (url != null) {
			File file = new File(serverrealPath + File.separator
					+ entity.getUrl());
			DeleteFile.deleteByFile(file);// 删除源文件
			entity.setUrl(url);
		}
		specialAttachmentDao.save(entity);
	}

	/**
	 * 批量删除
	 * 
	 * @param Entity
	 * @return
	 */
	public void deleteById(String ids) {
		String serverrealPath = ServletActionContext.getServletContext()
				.getRealPath("/upload");
		for (String id : ids.split(",")) {
			SpecialAttachment entity = this.getById(id.trim());
			File file = new File(serverrealPath + File.separator
					+ entity.getUrl());
			DeleteFile.deleteByFile(file);// 删除源文件
			specialAttachmentDao.delete(id.trim());
		}
	}

	public Page<SpecialAttachment> getByFilter(
			final Page<SpecialAttachment> page, List<PropertyFilter> filters) {
		return specialAttachmentDao.findPage(page, filters);
	}

	public Page<SpecialAttachment> getPage(final Page<SpecialAttachment> page) {
		return specialAttachmentDao.findPage(page);
	}

	public SpecialAttachmentDao getSpecialAttachmentDao() {
		return specialAttachmentDao;
	}

	@Autowired
	public void setSpecialAttachmentDao(
			SpecialAttachmentDao specialAttachmentDao) {
		this.specialAttachmentDao = specialAttachmentDao;
	}
}
